//
//  ST_SendAirshipViewController.swift
//  btvideo
//
//  Created by mac on 2020/11/18.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyAttributes

class ST_SendAirshipViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .clear
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(15)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        //        bi_small_btn
        
        
        
        root_view.addSubview(top_image_view)
        top_image_view.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(top_image_view.snp.width).dividedBy(1.94)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        
        root_view.addSubview(bi_small_btn)
        bi_small_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(titleLabel)
            make.width.equalTo(60)
            make.height.equalTo(24)
        }
        
        
        root_view.addSubview(airship_container)
        airship_container.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(top_image_view.snp.bottom).offset(20)
            make.height.equalTo(85+15+85)
        }
        
        let cell0 = SendAirshipCell()
        airship_container.addSubview(cell0)
        cell0.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.equalTo(85)
        }
        cell0.percent = 100
        
        
        let cell1 = SendAirshipCell()
        airship_container.addSubview(cell1)
        cell1.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
            make.height.equalTo(85)
            make.left.equalTo(cell0.snp.right).offset(15)
            make.width.equalTo(cell0)
        }
        cell1.percent = 200
        
        let cell2 = SendAirshipCell()
        airship_container.addSubview(cell2)
        cell2.snp.makeConstraints { (make) in
            make.height.width.left.equalTo(cell0)
            make.top.equalTo(cell0.snp.bottom).offset(15)
        }
        cell2.percent = 300
        
        let cell3 = SendAirshipCell()
        airship_container.addSubview(cell3)
        cell3.snp.makeConstraints { (make) in
            make.height.width.left.equalTo(cell1)
            make.bottom.equalTo(cell2)
        }
        cell3.percent = 400
        
        cell0.isSelected = true
        self.last_selected_airship = cell0
        
        cell0.addTarget(self, action: #selector(select_handle(sender:)), for: UIControl.Event.touchUpInside)
        cell1.addTarget(self, action: #selector(select_handle(sender:)), for: UIControl.Event.touchUpInside)
        cell2.addTarget(self, action: #selector(select_handle(sender:)), for: UIControl.Event.touchUpInside)
        cell3.addTarget(self, action: #selector(select_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        
        root_view.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(TIANCompatibleValue(value: 58))
            make.right.equalToSuperview().offset(TIANCompatibleValue(value: -57))
            make.height.equalTo(44)
            make.top.equalTo(airship_container.snp.bottom).offset(30)
        }
        
        root_view.addSubview(bottom_title_label)
        bottom_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(TIANCompatibleValue(value: 58))
            make.right.equalToSuperview().offset(TIANCompatibleValue(value: -57))
            make.height.equalTo(17)
            make.top.equalTo(sendBtn.snp.bottom).offset(20)
            make.bottom.equalToSuperview().offset(-10-BTSafeAreaBottom-15)
        }
        
        setup_bi_small()
        
        request_data()
    }
    
    @objc fileprivate func select_handle(sender:SendAirshipCell){
        
        if sender.isSelected{
            return
        }
        
        last_selected_airship?.isSelected = false
        sender.isSelected = true
        last_selected_airship = sender
        
        
    }
    
    var send_closure:((ST_ChooseAirshipCellModel)->())?
    
    @objc fileprivate func send_handle(){
        
        
        guard let model = self.last_selected_airship?.model else { return  }
        
        
        if model.coin > ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin.int ?? 0{
            
           
            ST_MaidWayManager.shared.source = .心动礼物
            
            ST_RechargeViewController.toast()
            
            
            return
        }
        
        goback_previous_controller(animated: false) {
            self.send_closure?(model)
        }
    }
    
    
    fileprivate func request_data(){
        
        JVrequest(PH.propsListApi, queue: nil,success:{ (json) in
            
            let list = json["data"].arrayValue.map { (itemJson) -> ST_ChooseAirshipCellModel in
                return ST_ChooseAirshipCellModel.init(fromJson: itemJson)
            }
            
            for(idx,itemView)  in self.airship_container.subviews.enumerated(){
                
                if let v = itemView as? SendAirshipCell , let m = list[safe:idx]{
                    v.model = m
                }
            }
            
            
            
        },failure: { (code, err) in
            
            self.toast(text: err)
        })
        
    }
    
    fileprivate func setup_bi_small(){
        
        let coin = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin ?? 0
        
        let str = " " + coin.string
        
        bi_small_btn.setTitleForAllStates(str)
        
        let font = bi_small_btn.titleLabel?.font ?? UIFont.systemFont(ofSize: 12)
        
        let w = str.width(withConstrainedHeight: 100, font: font)
        
        bi_small_btn.snp.updateConstraints { (make) in
            make.width.equalTo(w + 28 + 10)
        }
        
    }
    
    
    //    MARK: - Properties
    
    fileprivate lazy var close_view:UIControl = {
        let control = UIControl()
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var root_view_normal_height = 459 + BTSafeAreaBottom
    
    fileprivate lazy var root_view_unfold_height = 614 + BTSafeAreaBottom
    
    fileprivate lazy var unfold_of_root_view = false
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        control.cornerRadius = 15
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "心动礼物"
        control.textColor = UIColor(hexString: "#3A3A3A")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var bi_small_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.init(name: "DINPro-Black", size: 15)!
        //        control.borderColor = UIColor(white: 0, alpha: 0.1)
        //        control.borderWidth = 1
        control.setTitleColor(UIColor.init(hex: 0xFEC207), for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("bi_small")!)
        control.backgroundColor = .white
        control.cornerRadius = 12
        //        control.semanticContentAttribute = .forceRightToLeft
        //        control.addTarget(self, action: #selector(recordHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var top_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("Rectangletop"))
        return control
    }()
    
    
    fileprivate lazy var sendBtn:ST_BTGradientButton = {
        
        let control = ST_BTGradientButton()
        control.bgLayer.colors = [UIColor.init(hex: 0xF1D6A0),UIColor.init(hex: 0xEDC26A)].map({$0!.cgColor})
        control.bgLayer.endPoint = CGPoint.init(x: 0, y: 1)
        
        control.cornerRadius = 44/2.0
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.setTitleForAllStates("立刻使用配对几率提升100%")
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(send_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var bottom_title_label:UILabel = {
        
        let control = UILabel.init()
        
        let str = "对方拒绝或超过7天未接受则".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0xB6BCC8)!)])
        
        str.append("自动退回".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)),.textColor(UIColor.init(hex: 0xED3E58)!)]))
        
        control.attributedText = str
        
        return control
    }()
    
    fileprivate var airship_container = UIView()
    
    fileprivate var last_selected_airship :SendAirshipCell?
    
}




//MARK: - Event
extension ST_SendAirshipViewController{
    
    @objc fileprivate func close_handle(){
        goback_previous_controller()
    }
    
    
    
}



//MARK: - Cell
class SendAirshipCell: UIControl {
    
    override var isSelected: Bool{
        didSet{
            self.borderColor = isSelected ? UIColor.init(hex: 0xEDC16A) : UIColor.clear
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        self.cornerRadius = 10
        self.borderColor = UIColor.clear
        self.borderWidth = 1
        
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.width.equalTo(cover_image_view.snp.height)
            make.left.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.height.equalTo(20)
            make.left.equalTo(cover_image_view.snp.right).offset(10)
            make.top.equalTo(cover_image_view).offset(12)
        }
        
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.height.equalTo(17)
            make.left.equalTo(cover_image_view.snp.right).offset(10)
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
        }
        
        self.addSubview(icon_image_view)
        icon_image_view.snp.makeConstraints { (make) in
            make.right.top.equalToSuperview()
            make.width.equalTo(34)
            make.height.equalTo(16)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#B6BCC8")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var icon_image_view:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.set_back_image_for_all_states(ST_ImageUtils.imageName("airshipRightTopIcon")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium)
        control.setTitleColorForAllStates(UIColor.white)
        return control
    }()
    
    var percent = 0{
        didSet{
            
            let str = percent.string + "%"
            icon_image_view.setTitleForAllStates(str)
            
        }
    }
    
    var model:ST_ChooseAirshipCellModel?{
        didSet{
            
            guard let m = model else { return  }
            
            
            cover_image_view.pin_setImage(from: m.image.compress_small_image(width: 65*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = m.name
            
            content_label.text = m.coin.string + "甜心币"
            
        }
    }
    
    
    
    
    
}


//MARK: - Model
class ST_ChooseAirshipCellModel : NSObject{

    var coin : Int
    var detail : [ST_PropModel]
    var id : Int
    var image : String
    var imageOfButton : String
    var integral : String
    var isShow : Int
    var moreConf : String
    var name : String
    var ownNum : Int
    var sort : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
       
        coin = json["coin"].intValue
        
        detail = json["detail"].arrayValue.map({ (itemJson) -> ST_PropModel in
            return ST_PropModel.init(fromJson: itemJson)
        })
        
        id = json["id"].intValue
        image = json["image"].stringValue
        integral = json["integral"].stringValue
        isShow = json["is_show"].intValue
        moreConf = json["more_conf"].stringValue
        name = json["name"].stringValue
        ownNum = json["own_num"].intValue
        sort = json["sort"].intValue
        
        imageOfButton = json["image_button"].stringValue
        
        
        super.init()
    }
}




class ST_PropModel : NSObject{

    var coin : String
    var image : String
    var num : String

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        coin = json["coin"].stringValue
        image = json["image"].stringValue
        num = json["num"].stringValue
        
        super.init()
    }
    
}
